package com.clei.utils.log;

import com.clei.utils.DateUtil;
import com.clei.utils.FileUtil;
import com.clei.utils.PrintUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

/**
 * file logger
 *
 * @author Y
 * @date 2023-10-26
 */
public class FileLogger implements Logger {

    /**
     * BufferedWriter
     */
    private BufferedWriter bw;

    /**
     * FileLogger
     *
     * @param filePathType 路径类型 absolute/relative
     * @param logFile      日志文件
     */
    public FileLogger(String filePathType, String logFile) {
        String absolute = "absolute";
        boolean relative = !absolute.equals(filePathType);
        String filePath = relative ? System.getProperty("user.dir") + File.separator + logFile : logFile;
        try {
            File file = new File(filePath);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                boolean mkdirs = parentFile.mkdirs();
                if (!mkdirs) {
                    PrintUtil.log("创建文件夹失败 : {}", parentFile.getAbsolutePath());
                }
            }
            int limitSize = 1024 * 1024 * 100;
            if (file.exists() && file.length() > limitSize) {
                String dateStr = DateUtil.currentDateTimeNumeric();
                int dotIndex = filePath.lastIndexOf('.');
                String newFilePath = null;
                if (-1 == dotIndex) {
                    newFilePath = filePath + dateStr;
                } else {
                    newFilePath = filePath.substring(0, dotIndex) + dateStr + filePath.substring(dotIndex);
                }
                File newFile = new File(newFilePath);
                boolean rename = FileUtil.mv(file, newFile);
                if (!rename) {
                    PrintUtil.log("日志文件重命名失败 oldPath : {}, newPath : {}", filePath, newFilePath);
                }
            }
            FileWriter fw = new FileWriter(file, true);
            this.bw = new BufferedWriter(fw);
        } catch (Exception e) {
            PrintUtil.log("日志文件初始化错误 filePathType : {}, logFile : {}", filePathType, logFile, e);
        }
    }

    /**
     * log
     */
    @Override
    public void log() {
        log(Logger.EMPTY);
    }

    /**
     * log
     *
     * @param str str
     */
    @Override
    public void log(final String str) {
        try {
            bw.write(str);
            bw.newLine();
            bw.flush();
        } catch (Exception e) {
            PrintUtil.log("log error str : {}", str, e);
        }
    }

    /**
     * log 不换行
     *
     * @param str str
     */
    @Override
    public void logWithoutLine(String str) {
        try {
            bw.write(str);
            bw.flush();
        } catch (Exception e) {
            PrintUtil.log("log error str : {}", str, e);
        }
    }
}
